<template>
  <div class="todo-wrap">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>Todo App V3</span>
          <span>{{ dateString }}</span>
        </div>
      </template>
      <div class="desc">
        <span>AllTasks: {{ todos.length }}</span>
        <span>UndoneTasks: {{ undoneTodos.length }}</span>
        <span>DoneTasks: {{ doneTodos.length }}</span>
      </div>
      <div class="file">
        <el-input v-model="title" placeholder="Please input" @keyup.enter="addTodo" />
      </div>
      <div v-for="item in todos" :key="item.id" class="row">
        <el-checkbox v-model="item.done" />
        <span :class="['row-text', { through: item.done }]">{{ item.title }}</span>
        <el-button v-show="item.done" class="row-btn" type="danger" plain @click="delTodo(item.id)">删除</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { getDateStr } from '@/utils/common'
import { useTodoStore } from '@/stores'
import { storeToRefs } from 'pinia'

const dateString = getDateStr()

// 在 setup() 中调用 useStore() 之前不会创建 store
const todoStore = useTodoStore()

const title = ref('')

// 为了从 Store 中提取属性同时保持其响应式，您需要使用storeToRefs()。 它将为任何响应式属性创建 refs
// 后期使用state、getters需要追加 .value
const { todos, doneTodos, undoneTodos } = storeToRefs(todoStore)

const delTodo = (id: number) => {
  todoStore.deleteTodo(id)
}
const addTodo = () => {
  const value = title.value && title.value.trim()

  if (!value) return

  const ids = todos.value.map(todo => todo.id)
  const id = Math.max(...ids) + 1

  const payload = {
    id,
    title: value,
    done: false,
  }
  todoStore.addTodo(payload)

  title.value = ''
}
</script>
<style lang="less" scoped>
.todo-wrap {
  height: 100%;
  padding: 12px 16px;
  overflow: auto;
  .box-card {
    width: 50%;
    min-width: 700px;
  }
  .card-header {
    display: flex;
    justify-content: space-between;
    font-size: 24px;
  }
  .desc {
    display: flex;
    justify-content: space-between;
    font-size: 20px;
    color: #777;
    margin-bottom: 28px;
  }
  .file {
    margin-bottom: 22px;
  }
  .row {
    font-size: 20px;
    margin-bottom: 14px;
    display: flex;
    align-items: center;
  }
  .row-text {
    line-height: 1.4em;
    margin: 0 20px 0 10px;
    flex: 1;
    word-break: break-all;
    &.through {
      text-decoration: line-through;
    }
  }
  .row-btn {
  }
}
</style>
